<?php
/**
* Language class file.
*
* @author Federico Ramirez <fedekiller@gmail.com>
* @link http://code.google.com/p/akaikiwi/
* @copyright Copyright &copy; 2008-2011 Federico Ramirez
* @license http://www.opensource.org/licenses/mit-license.php MIT Licence
*/

/*
* This class will parse all language files
* and let you work with them
*/
class Language {
	private $lang;

	function __construct() {
		$this->lang = array();
	}

	/**
	 * Returns whether the library has been loaded with a language file
	 */
	public function is_loaded() {
		return count($this->lang) > 0;
	}

	/**
	 * Returns the whole language array
	 */
	public function get_lang_array() {
		return $this->lang;
	}

	/**
	 * Loads a language file
	 * @param String $language
	 * @param String $file
	 * @param boolean $reset
	 */
	function load($file, $language = NULL, $reset = FALSE) {
		if(strpos($file, ',') !== FALSE) {
			foreach(explode(',', $file) as $f) {
				$this->load(trim($f), $language, $reset);
			}
			return;
		}
		
		if($language == NULL) {
			$config = AkaiKiwi::loadLib('Config');
			$language = $config->get_item('defaultLanguage');
		}
		if($reset) {
			$this->lang = array();
		}
		if(!file_exists('app/lang/' . $language . '/' . $file . '_lang.php')) {
			throw new AkaikiwiException('Language file could not be loaded, file (app/lang/'.$language.'/'.$file.'_lang.php) not found.');
		}

		$lang = array();
		require_once 'app/lang/' . $language . '/' . $file . '_lang.php';
		foreach($lang as $k => $v) {
			$this->lang[$k] = $v;
		}
	}

	/**
	 * Loads all the language files inside the given language directory
	 * @param String $language
	 * @param boolean $reset
	 */
	function load_lang($language = NULL, $reset = FALSE) {
		if($language == NULL) {
			$config = AkaiKiwi::loadLib('Config');
			$language = $config->get_item('defaultLanguage');
		}

		if ($handler = opendir('app/lang/' . $language)) {
			while (FALSE !== ($file = readdir($handler))) {
				if ($file != "." && $file != ".." && strpos($file, '_lang.php') !== FALSE) {
					$f = explode('.', $file);
					$this->load($f[0], $language, $reset);
				}
			}
			closedir($handler);
		}
	}

	/**
	 * Get a language value
	 * @param String $key
	 * @throws AkaikiwiException
	 */
	public function get($key) {
		if(array_key_exists($key, $this->lang)) {
			return $this->lang[$key];
		} else {
			throw new AkaikiwiException('Invalid key for language array.');
		}
	}
}
